package com.learnyou.server.xingzuo.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
public class DataLogFilterUtil {

    /**
     * 获取登录用户远程主机ip地址
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    public static String getRequestInfo(HttpServletRequest request, JoinPoint joinPoint) {

        StringBuilder sb = new StringBuilder();
        sb.setLength(0);

        sb.append(request.getServerName());
        sb.append(' ');

        String addr = getIpAddr(request);
        sb.append(addr);
        sb.append(" - ");

        sb.append(request.getMethod());
        sb.append(' ');
        sb.append(request.getRequestURI());
        sb.append('?');

        Map<String, String[]> map = request.getParameterMap();
        if (map == null) {
            sb.append(' ');
        } else if (!map.isEmpty()) {
            for (Map.Entry<String, String[]> entry : map.entrySet()) {
                if (entry.getValue().length > 0) {
                    String[] strings = trimAllWhiteSpace(entry.getValue());
                    String vals = StringUtils.join(strings, ",");
                    sb.append(entry.getKey()).append('=').append(vals).append('&');
                }
            }
        }
        if (!request.getMethod().equalsIgnoreCase("GET")) {
            // json参数
            sb.append(" json args:").append(GsonUtils.obj2json(joinPoint.getArgs()));
        }
        return sb.toString();
    }

    public static String[] trimAllWhiteSpace(String[] strs) {
        int strsLen;
        if (strs == null || (strsLen = strs.length) == 0) {
            return strs;
        }
        final String[] newStr = new String[strsLen];
        for (int i = 0; i < strsLen; i++) {
            newStr[i] = org.springframework.util.StringUtils.trimAllWhitespace(strs[i]);
        }
        return newStr;
    }
}
